/*******************************************************************************
 * Copyright (c) 2011 Jovansonlee B. Cesar.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v2.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * 
 * Contributors:
 *     Jovansonlee B. Cesar - initial API and implementation
 ******************************************************************************/
package com.ivanceras.client.xml;

import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.ivanceras.shared.db.DAO;
import com.ivanceras.shared.exception.DatabaseException;

import name.pehl.totoe.xml.client.Document;
import name.pehl.totoe.xml.client.HasText;
import name.pehl.totoe.xml.client.Node;
import name.pehl.totoe.xml.client.XmlParser;
import name.pehl.totoe.xml.client.Element;

public class XmlDataProvider {
	
	Document document = null;
	
	public XmlDataProvider(String xmlString){
		setXmlDocData(xmlString);
	}
	
	public static String getDataXPath(String table, Integer page, Integer itemsPerPage){
		StringBuffer xpath = new StringBuffer();
		if(page != null && page <= 0){
			try {
				throw new DatabaseException("Page shoud be positive integer starting from 1");
			} catch (DatabaseException e) {
				e.printStackTrace();
			}
		}
		Integer offset = (page-1) * itemsPerPage;
		Integer end = offset+itemsPerPage;
		xpath.append("//data/model[@name='"+table+"']/row[position() >= "+offset+" and position() <= "+end+"]");
		return xpath.toString();
	}
	
	public void setXmlDocData(String xmlString){
		document = new XmlParser().parse(xmlString);
	}
	
	public DAO[] getDaoList(String table, Integer page, Integer itemsPerPage){
		String xpath = getDataXPath(table, page, itemsPerPage);
		System.out.println("xpath: "+xpath);
		List<Node> nodeList = document.selectNodes(xpath);
		DAO[] daoList = new DAO[nodeList.size()];
		System.out.println("rows: "+nodeList.size());
		for(int i = 0; i < nodeList.size(); i++){
			Node node = nodeList.get(i);
			DAO dao = new DAO(table);
			Map<String, String> attributes = ((Element)node).getAttributeValues();
			List<Node> attributeList = ((Element)node).getChildren();
			for(Node attNode : attributeList){
				String attribute = attNode.getName();
				String value = ((HasText)attNode).getText();
				dao.set_Value(attribute, value);
			}
			daoList[i] = dao;
		}
		return daoList;
	}

	
}
